package cn.xz.gobang.activity


import cn.xz.gobang.R
import cn.xz.gobang.base.BaseActivity
import cn.xz.gobang.bean.CommonLib
import cn.xz.gobang.bean.EventBusMessage
import cn.xz.gobang.bean.RoomSingle
import cn.xz.gobang.databinding.ActivityStartPlayBinding
import cn.xz.gobang.net.OkHttpUtil
import cn.xz.gobang.service.ServerManager
import cn.xz.gobang.service.ServerUtils
import cn.xz.gobang.util.ARouter
import cn.xz.gobang.util.AniUtil
import cn.xz.gobang.util.AppHelper
import cn.xz.gobang.util.ToastUtil
import okhttp3.FormBody
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class StartPlayActivity: BaseActivity<ActivityStartPlayBinding>(R.layout.activity_start_play)  {

    private var closeSer = true

    override fun initData() {
        //开服务
        ServerUtils.startServer()

        mDataBind.tvNow.text = CommonLib.UserIP
        //动画
        AniUtil.onDX(1000,mDataBind.tvDown)
        //初始化自己的数据
        val mRoomSingle = RoomSingle()
        mRoomSingle.num = 1
        mRoomSingle.black = CommonLib.UserIP
        CommonLib.mData = mRoomSingle
    }

    override fun initEvent() {
        //加入对战按钮
        mDataBind.tvJoin.setOnClickListener {
            val mFriendName = mDataBind.etIp.text.toString()
            if (mFriendName != ""){
                val newBody: RequestBody = FormBody.Builder()
                    .add("f_ip", CommonLib.UserIP)
                    .build()
                //连接一下对方服务器，看一下能否正常连接
                OkHttpUtil.toPost("http://${mFriendName}:8080/test",newBody,object : OkHttpUtil.RequestSuccess<String> {
                    override fun success(data: String?) {
                        if (data != null && data == "在线"){
                            mDataBind.tvJoin.post {
                                CommonLib.mFriends.add(mFriendName)
                                mDataBind.tvNow.text = "${mDataBind.tvNow.text.toString()}\n$mFriendName"
                                CommonLib.mData.num++
                                CommonLib.mData.white = mFriendName
                            }
                        }
                    }
                    override fun error() {
                    }

                },String::class.java)
            }else{
                ToastUtil.show("请输入对方昵称")
            }
        }
        //开始游戏
        mDataBind.tvPlay.setOnClickListener {
            CommonLib.mFriends.forEach {
                OkHttpUtil.toGet("http://${it}:8080/open")
            }
            closeSer = false
            ARouter.to(SingleActivity::class.java,true)
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (closeSer){
            //关闭服务
            ServerUtils.stopServer()
        }
    }


}